#-*- coding: utf8 -*-
from tutor.scripts import *
from tutor.plugins.sympy import *
from random import choice

funcs = {
    cos: (pi / 2, 3 * pi / 2),
    sin: (pi,),
    Lambda(x, x ** 2 - x): (1,),
}

while True:
    with display_block('Entradas'):
        _uv = [x, y]
        shuffle(_uv)
        u, v = _uv

        # Escolhe ponto e função
        _f, _pts = oneof(*funcs.items())
        valor = oneof(_pts)
        func = u * _f(v)

        # Testes de validade 
        assert _f(valor) == 0, (_f, valor, _f(valor))
        assert diff(_f(x), x).subs(x, valor) != 0

    with display_block('Resultados'):
        correta = ((0, valor) if u == x else (valor, 0))
        grad = [Lambda(x, y, diff(func, x)), Lambda(x, y, diff(func, y))]

        def iscritical((x, y)):
            return 0 == grad[0](x, y) == grad[1](x, y)

        mul = (pi if _f in [sin, cos] else 1)
        x0, y0 = correta[0] / mul, correta[1] / mul
        values = list(rfractions(set([x0, y0]), max_compl=5, force_pos=True, max_size=10))

        p2 = (choice(values) * mul * oneof(0, -1), choice(values) * mul)
        p3 = (choice(values) * mul * oneof(0, -1), choice(values) * mul)
        p4 = (choice(values) * mul * oneof(0, -1), choice(values) * mul)
        p5 = (choice(values) * mul, choice(values) * mul * oneof(0, -1))
        p6 = (choice(values) * mul, choice(values) * mul * oneof(0, -1))
        p7 = (choice(values) * mul, choice(values) * mul * oneof(0, -1))
        p8 = (choice(values) * mul, choice(values) * mul * oneof(0, -1))

        if any(map(iscritical, [p2, p3, p4, p5, p6, p7, p8])):
            continue
        break
